package com.opdar.athena.support.controllers.client;

import com.opdar.athena.support.base.Result;
import com.opdar.athena.support.entities.UserEntity;
import com.opdar.athena.support.service.UserService;
import com.opdar.platform.annotations.Request;
import com.opdar.platform.core.base.Context;
import com.opdar.platform.core.session.ISessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by shiju on 2017/8/25.
 */
@Controller
public class ClientApiController {

    @Autowired
    ISessionManager<Object> sessionManager;
    @Autowired
    UserService userService;

    @Request(value = "/client/login",version = 1, format = Request.Format.JSON)
    public Result login(String userName, String userPwd, String appId, String utmSource){
        if(!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(userPwd)){
            UserEntity user = userService.login(userName, userPwd);
            if(user != null){
                user.setAppId(appId);
                String token = UUID.randomUUID().toString();
                if(!StringUtils.isEmpty(utmSource))
                    user.setUtmSource(utmSource);
                Context.getRequest().getSession().setAttribute("token",token);
                long expire = 24*60*60*1000;
                sessionManager.set(token,user,expire);
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("token",token);
                return Result.valueOf(map);
            }
        }
        return Result.valueOf(1,"");
    }

    @Request(value = "/client/register",version = 1,format = Request.Format.VIEW)
    public Result register(String userName, String userPwd){
        if(!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(userPwd)){
            boolean ret = userService.regist(userName, userPwd);
            if(ret){
                UserEntity userEntity = userService.findByUserName(userName);
                if(userEntity != null){
                    userEntity.setUserPwd(null);
                    userEntity.setSalt(null);
                    return Result.valueOf(userEntity);
                }
            }
        }
        return Result.valueOf(1,"注册失败");
    }

}
